from oasys import db


class Base(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    def save(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()


class Deptment(Base):
    __tablename__ = 'deptment'
    name = db.Column(db.String(32))
    desc = db.Column(db.Text)
    positions = db.relationship('Position', backref='dept')


class Position(Base):
    __tablename__ = 'position'
    name = db.Column(db.String(32))
    level = db.Column(db.Integer)
    # 部门外键
    deptment_id = db.Column(db.Integer, db.ForeignKey('deptment.id'))
    employees = db.relationship('Employee', backref='position')


class Employee(Base):
    __tablename__ = 'employee'
    username = db.Column(db.String(32))
    password = db.Column(db.String(32))
    # 职位外键
    position_id = db.Column(db.Integer, db.ForeignKey('position.id'))
    attendances = db.relationship('Attendance', backref='employee')


# 考勤模型类
class Attendance(Base):
    __tablename__ = 'attendance'
    atype = db.Column(db.String(32), default='事假')
    astatus = db.Column(db.String(32), default='申请中')
    areason = db.Column(db.String(128))
    starttime = db.Column(db.String(128))
    endtime = db.Column(db.String(128))
    adate = db.Column(db.Integer)
    checkman = db.Column(db.String(32), default='')
    employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'))


pos_perm = db.Table(
    'pos_perm',
    db.Column('pos_id', db.Integer, db.ForeignKey('position.id')),
    db.Column('perm_id', db.Integer, db.ForeignKey('permission.id'))
)


class Permission(Base):
    __tablename__ = 'permission'
    name = db.Column(db.String(32))
    desc = db.Column(db.String(128))
    positions = db.relationship('Position', backref='permissions', secondary=pos_perm)
